/*
* Project : Linuxbox
* File    : AdminLogin.java
* Version : 1.0
* Author  : Kevin Zhang
*
* Copyright (c) 2000-2001 by Linuxbox, Inc.
* All rights reserved.
 */
package linuxbox.system.servlet;

import javax.servlet.http.*;

import org.apache.log4j.Logger;

import linuxbox.BoxStatic;
import linuxbox.common.*;
import linuxbox.admin.logic.*;
import linuxbox.exception.LinuxboxException;

public class AdminLoginAction extends Action {
  protected static Logger logger = Logger.getLogger(AdminLoginAction.class.getName());

  protected static final String NAME_PARAM = "NAME";
  protected static final String PASSWORD_PARAM = "PASSWORD";

  protected static String successJSP = null;
  protected static String failureJSP = null;

  //This is a special case to derive this doAction action, since this the first Action to be called,
  //there is no BoxSession exist yet
  public void doAction(HttpServletRequest req, HttpServletResponse res)
      throws Exception {
    String LoginID = req.getParameter("NAME");
    String Password = req.getParameter("PASSWORD");

    UserManager um = UserManager.getInstance();

    try {
      int userID = um.userLogin(LoginID, Password);
      User user = um.getUser(userID);
      String userName = BoxStatic.formater.formatName(
          user.getLastName(), user.getFirstName());
      BoxSession sec = new BoxSession(userID, LoginID, userName, user.getUserRights());
      // if service turned off, only admin can login
      if (!BoxStatic.serviceSwitch && !sec.isSystemAdmin()) {
        sendNoneJspFile(BoxStatic.SERVICE_OFF_PAGE, req, res);
        return;
      }

      HttpSession session = req.getSession(true);
      session.setAttribute(BoxStatic.BOX_SESSION, sec);

      /*sec = (BoxSession)session.getAttribute(BoxStatic.BOX_SESSION);
      if (sec == null)
        res.sendRedirect(failureJSP);
      res.sendRedirect(successJSP);*/

      if (logger.isDebugEnabled())
        logger.debug("Login succeeded. Redirect to " + successJSP);
      sendFile(successJSP, req, res);
//      redirectFile(successJSP, req, res);
    } catch (LinuxboxException e) {
      //redirectFile(failureJSP, req, res);

      if (logger.isDebugEnabled())
        logger.debug("Login failed. Redirect to " + failureJSP);
      req.setAttribute("ErrorMsg", "Login error, please login again!");

      sendNoneJspFile(failureJSP, req, res);
    }
  }

  public void setSuccessJSP(String str) {
    successJSP = str;
  }

  public void setFailureJSP(String str) {
    failureJSP = str;
  }
}